package com.prj.ufdm.web.config;

import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.prj.ufdm.core.util.UfdmStringUtil;
import com.github.pagehelper.PageInterceptor;

/**
 * 配置 ogjjMyBatis 
 * @author Administrator
 */
@Configuration
@MapperScan(basePackages = {"com.prj.ufdm.auth.dao","com.prj.ufdm.flow.dao"}, sqlSessionTemplateRef  = "mainDsSqlSessionTemplate")
public class MyBatisConfig {
	
	@Resource
    private Environment env;
    
    @Bean(name = "mainDsSqlSessionFactory")
    @Primary
    public SqlSessionFactory mainDsSqlSessionFactory(@Qualifier("mainDsDataSource") DataSource dataSource) throws Exception {
    	
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*/**/mybatis-*.xml"));
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", UfdmStringUtil.getDbType(env!=null ? env.getProperty("main.ds.driverClassName") : ""));
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("params", "count=countSql");
        pageInterceptor.setProperties(properties);
        sessionFactory.setPlugins(new Interceptor[]{pageInterceptor});
        return sessionFactory.getObject();
    }
    
    
    @Bean(name = "mainDsTransactionManager")
    @Primary
    public DataSourceTransactionManager mainDsTransactionManager(@Qualifier("mainDsDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mainDsSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate mainDsSqlSessionTemplate(@Qualifier("mainDsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    

}
